package com.seari.custody.controller;

import com.seari.custody.constant.MessageConstant;
import com.seari.custody.pojo.MessageBean;
import com.seari.custody.service.MeetingStatisticalService;
import com.seari.custody.util.HandlerNullUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("/meetingStatistical")
public class MeetingStatisticalController {

    @Autowired
    private MeetingStatisticalService meetingStatisticalService;

    private static SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @RequestMapping( "/countMeeting")
    public MessageBean countMeeting(@RequestBody Map<String,Object> map) {
        MessageBean messageBean = new MessageBean();
        Map<String, Object> dataMap = new LinkedHashMap<>();
        try {
            String startTime ="";
            String endTime ="";

            //开始时间
            if(!HandlerNullUtils.objectIsNull(map.get("startDate"))){
//                startTime=map.get("startTime")+"-01";//时间精确到月

                startTime=(String)map.get("startDate");//时间精确到日
            }
            //结束时间
            if(!HandlerNullUtils.objectIsNull(map.get("dateClosed"))){
//                endTime=(String)map.get("endTime");//精确到月
//                endTime=endTime+"-"+howManyDays(endTime);

                endTime=subDay((String)map.get("dateClosed"));//精确到日
            }
            dataMap=meetingStatisticalService.queryCountMeeting(startTime,endTime);
            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("查询成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("查询失败");
        }
        return messageBean;
    }





    @RequestMapping( "/meetingBar")
    public MessageBean meetingBar(@RequestBody Map<String,Object> map) {
        MessageBean messageBean = new MessageBean();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        try {
            String type = (String)map.get("type");
            String startTime ="";
            String endTime ="";

            //开始时间
            if(!HandlerNullUtils.objectIsNull(map.get("startDate"))){
                startTime=(String)map.get("startDate");
            }else{
                startTime=new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
            }
            //结束时间
            if(!HandlerNullUtils.objectIsNull(map.get("dateClosed"))){
                endTime=(String)map.get("dateClosed");
            }else{
                endTime=new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
            }

            List<String> typeList=new ArrayList<>();
            if("0".equals(type)){//全部
                typeList.add("1");
                typeList.add("2");
                typeList.add("3");
                typeList.add("4");
                typeList.add("5");
            }else if("1".equals(type)){//征询
                typeList.add("1");
                typeList.add("2");
                typeList.add("3");
                typeList.add("4");
            }else{
                typeList.add("5");
            }
            List<String> monthList=countMonths(startTime, endTime);

            Map<String,Object> formatMap=new HashMap<>();

            for(int i=0;i<monthList.size();i++){
                String month=monthList.get(i);
                List<Map<String,String>> list=new ArrayList<>();
                String start;
                String end;
                if(i==0){
                    start=startTime;
                    end=month+"-"+howManyDays(month);
                    list=meetingStatisticalService.queryMeetingBar(typeList,start,end);
                    dataMap=formatList(formatMap,list,month);
                }else if(i==monthList.size()-1){
                    start=month+"-01";
                    end=subDay(endTime);
                    list=meetingStatisticalService.queryMeetingBar(typeList,start,end);
                    dataMap=formatList(formatMap,list,month);
                }else{
                    start=month+"-01";
                    end=month+"-"+howManyDays(month);
                    list=meetingStatisticalService.queryMeetingBar(typeList,start,end);
                    dataMap=formatList(formatMap,list,month);
                }
            }

            messageBean.setType(MessageConstant.SUCCESS_TYPE);
            messageBean.setCode(MessageConstant.SUCCESS);
            messageBean.setMessage("查询成功 ");
            messageBean.setData(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            messageBean.setType(MessageConstant.FAIL_TYPE);
            messageBean.setCode(MessageConstant.FAIL);
            messageBean.setMessage("查询失败");
        }
        return messageBean;
    }





    /**
     * 计算间隔时间（单位：秒）
     * @return
     * @throws Exception
     */
    private static long countTime(String startTime,String endTime) throws Exception {
        Date begin=dfs.parse(startTime);
        Date end = dfs.parse(endTime);
        long between=(end.getTime()-begin.getTime())/1000;//除以1000是为了转换成秒
//        long day1=between/(24*3600);
//        long hour1=between%(24*3600)/3600;
//        long minute1=between%3600/60;
//        long second1=between%60/60;
//        System.out.println(between/(60*60)+"小时");
        return between;
    }

    /**
     * 根据年月判断日期
     * @param date
     * @return
     */
    private static int howManyDays (String date ) {
        Calendar calendar = Calendar.getInstance ();
        String[] dates = date.split ("[^\\d]");
        int year = Integer.parseInt (dates[0]);
        int month = Integer.parseInt (dates[1]) - 1;
        calendar.set (year, month, 1);
        return calendar.getActualMaximum (Calendar.DAY_OF_MONTH);
    }

    /**
     * 取出时间段内所有月份
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> countMonths(String startTime,String endTime) {
        try {
            Date startDate = new SimpleDateFormat("yyyy-MM").parse(startTime);
            Date endDate = new SimpleDateFormat("yyyy-MM").parse(endTime);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            // 获取开始年份和开始月份
            int startYear = calendar.get(Calendar.YEAR);
            int startMonth = calendar.get(Calendar.MONTH);
            // 获取结束年份和结束月份
            calendar.setTime(endDate);
            int endYear = calendar.get(Calendar.YEAR);
            int endMonth = calendar.get(Calendar.MONTH);
            List<String> list = new ArrayList<String>();
            for (int i = startYear; i <= endYear; i++) {
                String date = "";
                if (startYear == endYear) {
                    for (int j = startMonth; j <= endMonth; j++) {
                        if (j < 9) {
                            date = i + "-0" + (j + 1);
                        } else {
                            date = i + "-" + (j + 1);
                        }
                        list.add(date);
                    }

                } else {
                    if (i == startYear) {
                        for (int j = startMonth; j < 12; j++) {
                            if (j < 9) {
                                date = i + "-0" + (j + 1);
                            } else {
                                date = i + "-" + (j + 1);
                            }
                            list.add(date);
                        }
                    } else if (i == endYear) {
                        for (int j = 0; j <= endMonth; j++) {
                            if (j < 9) {
                                date = i + "-0" + (j + 1);
                            } else {
                                date = i + "-" + (j + 1);
                            }
                            list.add(date);
                        }
                    } else {
                        for (int j = 0; j < 12; j++) {
                            if (j < 9) {
                                date = i + "-0" + (j + 1);
                            } else {
                                date = i + "-" + (j + 1);
                            }
                            list.add(date);
                        }
                    }

                }

            }

            return list;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /****
     * 传入具体日期 ，返回具体日期减少一天
     * @param date
     * @return
     * @throws Exception
     */
    private  String subDay(String date) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt = sdf.parse(date);
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(dt);
        rightNow.add(Calendar.DAY_OF_MONTH, -1);
        Date dt1 = rightNow.getTime();
        String reStr = sdf.format(dt1);
        return reStr;
    }

    /**
     *整理柱状图数据结构
     * @param map
     * @param list
     * @param month
     * @return
     */
    public static Map<String,Object> formatList(Map<String,Object> map,List<Map<String,String>> list,String month) {
        try {
            List<String> monthList= map.get("xdata")==null?new ArrayList<>():(List<String>) map.get("xdata");
            monthList.add(month);
            List<Map<String,Object>> result = map.get("result")==null?new ArrayList<>() : (List<Map<String,Object>>) map.get("result");
            List<Integer> xsList = new ArrayList<>();
            List<Integer> xxnList= new ArrayList<>();
            List<Integer> xxwList= new ArrayList<>();

            for(Map<String,Object> re:result){
                String name = (String) re.get("name");//1 线上 2线下内 3线下外
                if ("线上会议".equals(name)) {
                    xsList= re.get("data")==null?new ArrayList<>():(List<Integer>) re.get("data");
                } else if ("线下内部会议".equals(name)) {
                    xxnList= re.get("data")==null?new ArrayList<>():(List<Integer>) re.get("data");
                } else if ("线下外部会议".equals(name)) {
                    xxwList= re.get("data")==null?new ArrayList<>():(List<Integer>) re.get("data");
                }
            }


            if(list.size()>0) {
                Map<String,Integer> data=new HashMap<>();
                data.put("1",0);
                data.put("2",0);
                data.put("3",0);
                data.put("4",0);
                for (Map<String, String> m : list) {
                    String b=String.valueOf(m.get("num"));
                    data.put(m.get("type"), Integer.parseInt(b));
                }
                xsList.add(data.get("1"));
                xxnList.add(data.get("2"));
                xxwList.add(data.get("3")+data.get("4"));//新增类型4 计入3
            }else {
                xsList.add(0);
                xxnList.add(0);
                xxwList.add(0);
            }
            Map<String,Object> xs=new HashMap<>();
            xs.put("name","线上会议");
            xs.put("data",xsList);
            Map<String,Object> xxn=new HashMap<>();
            xxn.put("name","线下内部会议");
            xxn.put("data",xxnList);
            Map<String,Object> xxw=new HashMap<>();
            xxw.put("name","线下外部会议");
            xxw.put("data",xxwList);
            result.clear();
            result.add(xs);
            result.add(xxn);
            result.add(xxw);
            map.put("xdata",monthList);
            map.put("result",result);
            return map;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }







}
